package com.mantou.mantouaiagent.config.redis;


import org.springframework.ai.chat.messages.Message;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

/**
 * Redis 配置类
 *
 * @author Silas Yan 2025-05-10 20:21
 */
@Configuration
public class RedisConfig {


	@Bean(value = "messageRedisTemplate")
	public RedisTemplate<String, Message> messageRedisTemplate(RedisConnectionFactory redisConnectionFactory, Jackson2ObjectMapperBuilder builder) {
		RedisTemplate<String, Message> template = new RedisTemplate<>();
		template.setConnectionFactory(redisConnectionFactory);

		// 使用String序列化器作为key的序列化方式
		template.setKeySerializer(new StringRedisSerializer());
		// 使用自定义的Message序列化器作为value的序列化方式
		template.setValueSerializer(new CustomMessageSerializer(builder.build()));

		// 设置hash类型的key和value序列化方式
		template.setHashKeySerializer(new StringRedisSerializer());
		template.setHashValueSerializer(new CustomMessageSerializer(builder.build()));
		template.afterPropertiesSet();
		return template;
	}

	@Bean
	public RedisTemplate<String, String> stringRedisTemplate(RedisConnectionFactory redisConnectionFactory, Jackson2ObjectMapperBuilder builder) {
		RedisTemplate<String,String> redisTemplate = new RedisTemplate<>();

		redisTemplate.setConnectionFactory(redisConnectionFactory);
		//设置key序列化方式string
		redisTemplate.setKeySerializer(new StringRedisSerializer());
		//设置value的序列化方式json，使用GenericJackson2JsonRedisSerializer替换默认序列化
		redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

		redisTemplate.setHashKeySerializer(new StringRedisSerializer());
		redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

		redisTemplate.afterPropertiesSet();

		return redisTemplate;
	}
}
